<?php
defined('SYSPATH') or die('No direct script access.');

class Model_Supplier extends ORM{

	protected $_table_name  = 'supplier';
	protected $_table_names_plural = false;
	private $default_img = "default.png";
	private $isStartMap = false;
	private $userLat;
	private $userLon;

	public function areaList(){
		return DB::query(Database::SELECT, 'SELECT road FROM supplier group by road')->execute();
	}
	public function consume(){
		$this->consumerecord = $this->consumerecord + 1;
		return $this->save();
	}

	public function insert($dataArray){
		$fileUtil = FileUtil::Factory();
		$fileName = $fileUtil->saveFile($this->defaultImgPath());
		if ($fileName != FALSE){
			$dataArray["picture"] = $fileUtil->getFilePath($fileName);
		}else{
			$dataArray["picture"] = $this->default_img;
		}
		$dataArray["jointime"] = Date::formatted_time();
		$dataArray["modifytime"] = Date::formatted_time();
		$dataArray["city"] = 1;
		$dataArray["status"] = "A";
		if($this->values($dataArray)->check()){
			return $this->save();
		}
		return false;
	}

	public function update($dataArray){
		$fileUtil = FileUtil::Factory();
		$dataArray["picture"] = $fileUtil->getFilePath($fileUtil->saveFile($this->defaultImgPath()),'picture');
		if (!empty($dataArray['picture'])){
			if ($dataArray['picture']!=$this->picture){
				if (!empty($this->picture) && $this->picture != $this->default_img){
					$orginal_real_path = $this->defaultImgPath().DIRECTORY_SEPARATOR.$this->picture;
					$fileUtil->deleteFile($orginal_real_path);
				}
				$this->picture = $dataArray['picture'];
			}
		}
		$this->sup_cate_id=$dataArray["sup_cate_id"];
		$this->name=$dataArray["name"];
		$this->address=$dataArray["address"];
		$this->road=$dataArray["road"];
		$this->phone=$dataArray["phone"];
		$this->phone2=$dataArray["phone2"];
		$this->telephone=$dataArray["telephone"];
		$this->telephone2=$dataArray["telephone2"];
		$this->starttime=$dataArray["starttime"];
		$this->endtime=$dataArray["endtime"];
		$this->leastprice=$dataArray["leastprice"];
		$this->leastdistance=$dataArray["leastdistance"];
		$this->avgprice=$dataArray["avgprice"];
		$this->sort=$dataArray["sort"];

		$this->deliverydesc=$dataArray["deliverydesc"];
		$this->desc=$dataArray["desc"];
		$this->modifytime=Date::formatted_time();

		return $this->save();
	}
	
	public function markMap($dataArray){
		$this->map_address = $dataArray["address"];
		$this->longitude = $dataArray["longitude"];
		$this->latitude = $dataArray["latitude"];
		$this->modifytime=Date::formatted_time();
		return $this->save();
	}

	public function updateModifyTime(){
		$this->modifytime=Date::formatted_time();
		return $this->save();
	}

	public function getResult($filters){
		if (array_key_exists("page", $filters)){
			$result = $this->getResultByPagination($filters);
		}else{
			$result = $this->modelWithCondition($filters)->find_all();
		}
		return $result;
	}

	private function getResultByPagination($filters){
		$attrArray["total_items"] = $this->getResultCount($this->modelWithCondition($filters));
		$page = $filters["page"];
		if (array_key_exists("pageSize", $filters)){
			$attrArray["items_per_page"] = $filters["pageSize"];
		}
		$pagination = Pagination::factory($attrArray);
		if ($page <= $pagination->total_pages){
			$result = $this->modelWithCondition($filters)->limit($pagination->items_per_page)->offset($pagination->offset)->find_all();
		}
		else{
			$result = array();
		}
		return $result;
	}

	private function modelWithCondition($filters){
		$model = $this->where("status","=","A");
		if (array_key_exists("supCateId", $filters)){
			$model = $this->and_where("sup_cate_id","=",$filters["supCateId"]);
		}
		if (array_key_exists("longitude", $filters) && array_key_exists("latitude", $filters)){
			$this->userLon = $filters["longitude"];
			$this->userLat = $filters["latitude"];
			$this->isStartMap = true;
		}
		if (array_key_exists("road", $filters)){
			$road = $filters["road"];
			if (!$this->iS_Utf8($road)){
				$road = mb_convert_encoding($road, "utf-8", "gb2312");
			}
			$model = $model->and_where("road","=",$road);
		}
		if (array_key_exists("qtxt", $filters)){
			$searchText = $filters["qtxt"];
			if (!$this->iS_Utf8($searchText)){
				$searchText = mb_convert_encoding($searchText, "utf-8", "gb2312");
			}
			$dishResult = ORM::factory("dish")->where("name","like",'%'.$searchText.'%')->find_all()->as_array();
			$ids_array = array();
			foreach ($dishResult as $dishItem){
				if (!in_array($dishItem->supplierid, $ids_array)){
					array_push($ids_array, $dishItem->supplierid);
				}
			}
			$model = $model->and_where("name","like",'%'.$searchText.'%');
			if (sizeof($ids_array) > 0){
				$model = $model->or_where_open()
				->and_where_open();
			}
			foreach ($ids_array as $id){
				$model = $model->or_where("id","=",$id);
			}
			if (sizeof($ids_array) > 0){
				$model = $model->or_where_close()
				->and_where("status","=","A")
				->and_where_close();
			}
		}
		if (array_key_exists("isSelling", $filters)){
			$isSelling = $filters["isSelling"];
			$today = getdate();
			$currentHour = $today["hours"];
			if($currentHour == 0){
				$currentHour = 24;
			}
			if ($isSelling == "y" ||$isSelling == "Y" ){
				$model = $model->and_where_open()
				->and_where_open()
				->where("starttime","<","endtime")
				->and_where("starttime","<=",$currentHour)
				->and_where("endtime",">",$currentHour)
				->and_where_close()
				->or_where_open()
				->where("starttime",">=","endtime")
				->and_where("starttime","<=",$currentHour)
				->and_where("endtime",">",$currentHour -24)
				->or_where_close()
				->and_where_close();
			}else if($isSelling == "n" ||$isSelling == "N" ){
				$model = $model->and_where_open()
				->and_where_open()
				->where("starttime","<","endtime")
				->and_where_open()
				->where("starttime",">",$currentHour)
				->or_where("endtime","<=",$currentHour)
				->and_where_close()
				->and_where_close()
				->or_where_open()
				->where("starttime",">=","endtime")
				->and_where_open()
				->where("starttime",">",$currentHour)
				->or_where("endtime","<=",$currentHour - 24)
				->and_where_close()
				->or_where_close()
				->and_where_close();
			}
		}
		return $model->order_by('sort','ASC')->order_by('jointime','DESC');
	}

	private function getResultCount($model){
		return $model->count_all();
	}

	private function iS_Utf8($value)
	{
		if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$value) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$value) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$value) == true)
		{
			return true;
		}
		else
		{
			return false;
		}

	}
	
	private function defaultImgPath(){
		return $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.Upload::$default_directory.DIRECTORY_SEPARATOR.'supplier';
	}
	
	public function displayStatus(){
		if ($this->status == "A" || $this->status == "a"){
			return "审核通过";
		}else if ($this->status == "P" || $this->status == "p"){
			return "正在审核";
		}else if ($this->status == "F" || $this->status == "f"){
			return "审核失败";
		}else{
			return "已删除";
		}
	}
	
	public function displayOpen(){
		if ($this->starttime == 1 && $this->endtime == 24){
			$text = "24小时营业";
		}else{
			$text = "从".$this->starttime.":00 至";
			if($this->starttime > $this->endtime){
				$text = $text."次日";
			}
			$text = $text.$this->endtime.":00";
		}
		return $text;
	}
	
	public function displaySupplierName(){
		return '['.$this->id.']-'.$this->name;
	}
	
	/**
	 * Loads a database result, either as a new object for this model, or as
	 * an iterator for multiple rows.
	 * 重写此方法
	 * @chainable
	 * @param   boolean       return an iterator or load a single row
	 * @return  ORM           for single rows
	 * @return  ORM_Iterator  for multiple rows
	 */
	protected function _load_result($multiple = FALSE)
	{
		$this->_db_builder->from($this->_table_name);

		if ($multiple === FALSE)
		{
			// Only fetch 1 record
			$this->_db_builder->limit(1);
		}

		// Select all columns by default
		if (!$this->isStartMap){
			$this->_db_builder->select($this->_table_name.'.*,"" as distance');
		}else{
			$this->_db_builder->select($this->_table_name.'.*,convert(
			( 6371 * acos( cos( radians( '.$this->userLat.' ) ) * cos( radians( latitude ) ) 
			* cos( radians( longitude ) - radians( '.$this->userLon.' ) ) + sin( radians( '.$this->userLat.' ) )
	 		* sin( radians( latitude ) ) ) ),decimal(3,2)) AS distance');
		}
		

		if ( ! isset($this->_db_applied['order_by']) AND ! empty($this->_sorting))
		{
			foreach ($this->_sorting as $column => $direction)
			{
				if (strpos($column, '.') === FALSE)
				{
					// Sorting column for use in JOINs
					$column = $this->_table_name.'.'.$column;
				}

				$this->_db_builder->order_by($column, $direction);
			}
		}
		if (!empty($this->userLat) && !empty($this->userLon)){
			$this->_db_builder->order_by("distance", "asc");
		}

		if ($multiple === TRUE)
		{
			// Return database iterator casting to this object type
			$result = $this->_db_builder->as_object(get_class($this))->execute($this->_db);

			$this->reset();

			return $result;
		}
		else
		{
			// Load the result as an associative array
			$result = $this->_db_builder->as_assoc()->execute($this->_db);

			$this->reset();

			if ($result->count() === 1)
			{
				// Load object values
				$this->_load_values($result->current());
			}
			else
			{
				// Clear the object, nothing was found
				$this->clear();
			}

			return $this;
		}
	}
	
}